<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>vue学习</title>
    <script src="./js/vue.js"></script>
    <style>
      .form {
        margin-bottom: 20px;
        border-bottom: 1px solid #ccc;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <div class="form">
        <div>
          商品名称:
          <input type="text" v-model="form.name" />
        </div>
        <div>
          商品价格:
          <input type="number" v-model="form.price" />分
        </div>
        <div>
          <button @click="saveData">保存数据</button>
        </div>
      </div>
      <div>
        <table border="1" width="600">
          <thead>
            <tr>
              <th>
                <input type="checkbox" @change="changeAllHandle" />
              </th>
              <th>序号</th>
              <th>名称</th>
              <th>价格</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item,index in goods" :key="item.id">
              <td>
                <input type="checkbox" :value="item.id" v-model="checkedIds" />
              </td>
              <td>{{index+1}}</td>
              <td>{{item.name}}</td>
              <td>{{item.price}}</td>
              <td>
                <button @click="delItem(index)">删除</button>
              </td>
            </tr>
          </tbody>
        </table>
        <hr />
        <!-- <h3>合计：{{totalPrice()}}</h3> -->
        <h3>合计：{{totalPriceNum}}</h3>
      </div>
    </div>
    <script>
      const app = Vue.createApp({
        data() {
          return {
            form: {
              name: '',
              price: 1000
            },
            checkedIds: [],
            goods: [],
            totalPriceNum: 0
          }
        },
        methods: {
          // 保存数据
          saveData() {
            this.goods.push({
              id: Date.now(),
              ...this.form
            })
            this.form = {
              name: '',
              price: 1000
            }
          },
          // 删除指定的行数据
          delItem(index) {
            this.goods.splice(index, 1)
          },
          // 是否全选
          changeAllHandle(e) {
            let checked = e.target.checked
            // 勾选上了
            if (checked) {
              this.checkedIds = this.goods.map((item) => item.id)
              // 只有选中了才进行计算
              this.totalPriceNum = this.totalPrice()
            } else {
              this.checkedIds = []
              this.totalPriceNum = 0
            }
          },
          totalPrice() {
            return this.goods.reduce((prev, curr) => {
              prev += curr.price
              return prev
            }, 0)
          }
        }
      })
      app.mount('#app')
    </script>
  </body>
</html>
